<?php
$url = "/admin/index.php";
if(file_exists('../config.php')) {
  	Header("Location: $url"); 
}
header("Content-Type:text/html; charset=utf-8");
$DB = trim($_POST["DB"]);
$DB_USER = trim($_POST["DB_USER"]);
$DB_PWD = trim($_POST["DB_PWD"]);
$DB_HOST = trim($_POST["DB_HOST"]);
$SITE = trim($_POST["SITE"]);
$CONFIG = array(
        'DB_HOST' => $DB_HOST,
        'DB_PORT' => '3306',
        'DB_NAME' => $DB,
        'DB_USER' => $DB_USER,
        'DB_PWD'  => $DB_PWD,
        'SITE_NAME' => $SITE,
        'PATH_MOD'=> 'NORMAL',
        'USERS' => array(
            'admin' => 'admin',
        )
    );
$SQL1 = <<<EOT
--
-- 表的结构 `history`
--

CREATE TABLE IF NOT EXISTS `history` (
  `id` int(11) NOT NULL,
  `type` tinyint(1) NOT NULL COMMENT '1普通，2元年，3头条',
  `startDate` datetime NOT NULL,
  `endDate` datetime DEFAULT NULL,
  `headline` varchar(50) NOT NULL,
  `text` text NOT NULL,
  `tag` varchar(255) DEFAULT NULL,
  `asset` text NOT NULL,
  `status` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
EOT;

$SQL2 = <<<EOD
--
-- 表的结构 `timeline`
--

CREATE TABLE IF NOT EXISTS `timeline` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `type` tinyint(1) NOT NULL COMMENT '1普通，2元年，3头条',
  `startDate` datetime NOT NULL,
  `endDate` datetime DEFAULT NULL,
  `headline` varchar(50) NOT NULL,
  `text` text NOT NULL,
  `tag` varchar(255) DEFAULT NULL,
  `asset` text NOT NULL,
  `status` int(11) NOT NULL DEFAULT '0' COMMENT '0草稿 1正式',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=50 ;
EOD;

$SQL3 = <<<EOM
CREATE TABLE IF NOT EXISTS `user` (
  `username` varchar(20) NOT NULL,
  `password` varchar(50) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
EOM;

function exist_DB($db){
	$dbs = mysql_query("SHOW DATABASES");
	$flag = false;
	while($row = mysql_fetch_array($dbs)) {
		if($row[0] == $db){
			$flag = true;
		}
	}
	return $flag;
}

if(isset($SITE) && isset($DB) && isset($DB_USER) && isset($DB_PWD) && isset($DB_HOST)){
	 $link = mysql_connect($DB_HOST, $DB_USER, $DB_PWD) or die('Could not connect: ' . mysql_error());
	 if($link){
		if(exist_DB($DB)){  //如果数据库存在
			$dblink = mysql_select_db($DB) or die("数据库".$DB."连接失败！");
		 	$tables = mysql_query("SHOW TABLES");
			$tbcount = mysql_fetch_array($tables);
			if($tbcount != false){
				echo "数据库已存在，且不为空，请修改数据库名或清除已建数据库的所有表";
				return false;
			}
		}else{  //如果数据库不存在，创建之
			mysql_query("CREATE DATABASE ".$DB, $link) or die("Could not create!");
		}
		mysql_query($SQL1, $link) or die("数据库的表history创建失败！" . mysql_error());
		mysql_query($SQL2, $link) or die("数据库的表timeline创建失败！" . mysql_error());
		mysql_query($SQL3, $link) or die("数据库的表user创建失败！" . mysql_error());
		mysql_close($link);
		$str = '<?php return ' . var_export($CONFIG, true) . ';';
		file_put_contents('../config.php', $str);
		echo "<script>alert('数据库创建成功'); window.location.href='setconfig.php';</script>";
	}else{
		echo "无法连接数据库，请检查用户名、密码以及主机是否正确！";
		return false;
	}	 
}



?>